package com.haidechizi.leetcode;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.Stack;

public class _90_子集II {

    public List<List<Integer>> subsetsWithDup(int[] nums) {
        Set<List<Integer>> result = new HashSet<>();
        Stack<Integer> stack = new Stack<>();
        Arrays.sort(nums);


        generate(0, nums, result, stack);
        List<List<Integer>> list = new ArrayList<>();
        list.add(new ArrayList<>());
        list.addAll(result);
        return list;
    }

    private void generate(int i, int[] nums, Set<List<Integer>> result, Stack<Integer> stack) {
        if (i >= nums.length) {
            return;
        }
        stack.push(nums[i]);
        addResult(result, stack);
        generate(i + 1, nums, result, stack);
        stack.pop();
        generate(i + 1, nums, result, stack);
    }

    private void addResult(Set<List<Integer>> result, Stack<Integer> stack) {
        List<Integer> list = new ArrayList<>();
        list.addAll(stack);
        result.add(list);
    }
}
